﻿using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Deeper.Common
{

	public static class ReflectionHelper
	{
		/// <summary>
		/// 得到某对象的属性值
		/// </summary>
		public static object GetPropertyValue(this object data, string propertyName)
		{
			if (data.IsNull()) throw new ArgumentNullException("取值的对象不能为空值");
			if (propertyName.IsNull()) throw new ArgumentNullException("属性名不能为空");

			Type type = data.GetType();
			string CacheKey = string.Format("Type_{0}", type.ToString());
			List<PropertyInfo> list = CacheKey.GetCache() as List<PropertyInfo>;

			if (list.IsNull())
				list = type.GetProperties().ToList();

			PropertyInfo pi = list.Find<PropertyInfo>(s => s.Name.Equals(propertyName));

			if (pi == null) throw new ArgumentException(propertyName + "属性不在这个类型中");
			else CacheKey.SetCache(pi);


			object propertyValue = pi.GetValue(data, null);
			return propertyValue;
		}

		/// <summary>
		/// 获取对象属性，或者属性的属性，用.分割
		/// </summary>
		/// <param name="data"></param>
		/// <param name="propertyName"></param>
		/// <returns></returns>
		public static object GetSubPropertyValue(this object data, string propertyName)
		{
			IList<string> list = propertyName.Split('.').Where(s => s.Length > 0).ToList();
			switch (list.Count)
			{
				case 0:
					return null;
				case 1:
					return data.GetPropertyValue(list[0]);
				default:
					object obj = data;
					for (int i = 0; i < list.Count; i++)
					{
						obj = obj.GetPropertyValue(list[i]);
					}
					return obj;
			}
		}
	}
}
